package mail.util;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.mail.Address;
import javax.mail.Message;
import javax.mail.Multipart;

/**
 * A class that is used for extracting the content of a message
 * 
 * @author Jonas Lindmark
 */
public class MessagePrinter {
    /**
     * Extract a mail
     * 
     * @param message
     * @return
     * @throws Exception 
     */
    public static Mail extractMail(Message message) throws Exception
    {
        Mail mail = new Mail();
        Address[] address;
        if ((address = message.getFrom()) != null)
        {
            for (int j = 0; j < address.length; j++)
            {
                mail.setFrom(mail.getFrom() + address[j].toString());
            }
        }
        if ((address = message.getRecipients(Message.RecipientType.TO)) != null)
        {
            for (int j = 0; j < address.length; j++)
            {
                mail.setTo(mail.getTo() + address[j].toString());
            }
        }
        String subject = message.getSubject();
        mail.setSubj(subject);
        String content = message.getContent().toString();
        String messageText = getContent(message);
        mail.setBody(messageText);
        return mail;
    }
    /**
     * Get a String representation of a Message
     * 
     * @param msg
     * @return 
     */
    public static String getContent(Message msg)
    {
        StringBuilder sb = new StringBuilder();
        try
        {
            Object content = msg.getContent();
            if (content instanceof Multipart)
            {
                Multipart mp = (Multipart) content;
                OutputStream output = new OutputStream()
                {
                    private StringBuilder sb = new StringBuilder();
                    @Override
                    public void write(int b) throws IOException {
                        this.sb.append((char) b );
                    }
                    @Override
                    public String toString(){
                        return this.sb.toString();
                    }
                };
                mp.writeTo(output);
                sb.append(output.toString());
            } else if (content instanceof String){
                sb.append((String)content);
            } else  if (content instanceof InputStream){
                InputStream stream = (InputStream)content;
                while (stream.available() != 0) {
                    sb.append((char)stream.read());
                }
            } else {
                throw new Exception("Content type not handled: " + content.getClass());
            }
        }
        catch (Exception ex)
        {
            System.out.println("Exception arise at get Content");
            ex.printStackTrace();
        }
        return sb.toString();
    }
}
